#include "evdeploy/runtime/ascend/atlas_base.h"
#define EV_ID_MAXLEN (1024)
namespace ev
{

    EVAscendModel::EVAscendModel() { EVLOG(INFO) << "this is a ascend engine"; }

    EVAscendModel::~EVAscendModel() {}

    void EVAscendModel::SetContext(void *context) { m_acl_context = (aclrtContext *)context; }

    void EVAscendModel::LoadModel(const char *model_name)
    {
        auto ret = aclrtSetCurrentContext(*m_acl_context);
        if (ret != 0)
        {
            EVLOG(INFO) << "failed to set context";
        }

        std::string soc_version = aclrtGetSocName();
        std::string input_model_name = std::string(model_name);
        std::string output_model_name = input_model_name.substr(0, input_model_name.size() - 5) + "." + soc_version;
        std::string om_model_name = output_model_name + ".om";
        EVLOG(INFO) << "trying to load model : " << om_model_name;
        if (ev::CheckFileType(om_model_name.c_str()) == ev::EV_NOT_EXIST)
        {
            EVLOG(INFO) << "om model not exist:" << om_model_name;
            if (ev::CheckFileType(input_model_name.c_str()) == ev::EV_FILE &&
                input_model_name.find(".onnx") != std::string::npos)
            {
                EVLOG(INFO) << "trying to convert onnx model:" << input_model_name;
                // atc 转换命令，命令参数cmd_str可修改
                std::string cmd_str = "atc --framework=5 --model=" + input_model_name +
                                      " --output=" + output_model_name + " --soc=" + soc_version;
                ConvertEngine(input_model_name, output_model_name, cmd_str);
                EVLOG(INFO) << "using new om model:" << om_model_name;
            }
            else
            {
                EVLOG(ERROR) << "No correct model exist, please check!!" << input_model_name;
                exit(0);
            }
        }
        else
        {
            EVLOG(INFO) << "using model:" << om_model_name;
        }

        ret = m_model_handle.loadModel(om_model_name, m_model_id);
        if (ret != 0)
        {
            EVLOG(ERROR) << "error in load model,please check";
            exit(0);
        }
    }

    void EVAscendModel::ConvertEngine(const std::string &input_model_name, const std::string &output_model_name,
                                      const std::string &cmd_str)
    {
        int ret = m_model_handle.convertOM(input_model_name, output_model_name, cmd_str);
        if (ret != 0)
        {
            EVLOG(ERROR) << "error in converting om model,please check";
            exit(0);
        }
    }

} // namespace ev
